package  net.dgg.dggcloud.service.jrcrm.utils;

import net.dgg.dggcloud.core.cache.CacheOperator;
import net.dgg.dggcloud.service.jrcrm.constant.CommonConstant;
import org.apache.commons.collections.map.HashedMap;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.*;


/**
 * 获取在线在线列表
 * @author liulei
 *
 */
public class SingleOnlineUser {

    private static CacheOperator cacheOperator;

    private static JedisCluster jedisCluster;

    static {
        String servers = ResourceUtils.getResource("redis").getValue("redis.servers");
        String[] hostandports = servers.split(";");
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        for (String recore : hostandports) {
            String server = recore.split(":")[0];
            String port = recore.split(":")[1];
            HostAndPort hostAndPort = new HostAndPort(server, Integer.valueOf(port));
            jedisClusterNodes.add(hostAndPort);
        }
        jedisCluster = new JedisCluster(jedisClusterNodes);
    }


    /**
     * 在线用户
     * @return
     */
    public static Map<String,Long> getMapOnline() {
        Map<String,String> onlineUser =jedisCluster.hgetAll(CommonConstant.ONLINE_USER);// cacheOperator.get(CommonKey.ONLINE_USER,Map.class);
        Map<String, Long> mapOnline = new HashMap<>();
        if(onlineUser != null){
            for(Map.Entry<String,String> entry : onlineUser.entrySet()){
                mapOnline.put((entry.getKey()).split(":")[1], Long.parseLong(entry.getValue()));
            }
        }
        return mapOnline;
    }

    /**
     * 在线用户 直接使用jredis
     *
     * @return
     */
    public static Map<String, Long> getMapOnlineByJedisCluster() {
        Map<String, String> map = jedisCluster.hgetAll(CommonConstant.ONLINE_USER);
        Map<String, Long> reMap = new HashedMap(10000);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            reMap.put(entry.getKey().split(":")[1], Long.valueOf(entry.getValue()));
        }
        return reMap;
    }

    /**
     * 在线用户 直接使用jredis
     *
     * @return
     */
    public static Map<String, String> getMapOnlineNameByJedisCluster() {
        Map<String, String> map = jedisCluster.hgetAll(CommonConstant.ONLINE_USER_NAME);
        Map<String, String> reMap = new HashedMap(10000);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            reMap.put(entry.getKey().split(":")[1], entry.getValue());
        }
        return reMap;
    }


}
